<?php
/**
 * @author spenceryg
 * @date 2023/6/20
 * @time 12:52 下午
 * @focus love & life
 */


namespace app\api1\controller;


use app\common\lib\WxTemplateMsg;
use app\common\model\Orders;
use app\common\model\PointProducts;
use app\common\model\RobotsGptToken;
use GuzzleHttp\Client;
use think\facade\Db;
use think\facade\Log;
use hg\apidoc\annotation as Apidoc;

class Test extends \app\BaseController
{
    public function chat()
    {
        header('X-Accel-Buffering: no');
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');

        //跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type');

        set_time_limit(0); //防止超时
        ob_end_clean();
        ob_implicit_flush(1);






        $event_name = input('event_name', 'chat', 'trim');
        if (!$event_name) {
            return error('事件名称能为空', []);
        }



        $client = new Client([
            'base_uri' =>'http://43.163.219.128:8000',
            'timeout' => 80,
        ]);



        try {
            $res = $client->request('post', '/chat', [
                'stream' => true,
                'json' => [
                    'input' => input('msg')
                ],
            ]);
        } catch (\Exception $e) {
            $msg = $e->getResponse()->getReasonPhrase();
            $c = "event:{$event_name}" . PHP_EOL; //定义事件
            $c .= "data:".$msg . PHP_EOL; //推送内容
            echo $c . PHP_EOL;

            $c = "event:{$event_name}" . PHP_EOL; //定义事件
            $c .= "data:end" . PHP_EOL; //推送内容
            echo $c . PHP_EOL;
        }




        $body = $res->getBody();
        $remainder = '';
        while (!$body->eof()) {
            $chunk = $body->read(2);

            // 合并剩余的字符和当前的数据块
            $chunk = $remainder . $chunk;

            // 处理完整的字符
            while (mb_strlen($chunk, 'UTF-8') > 1) {
                $char = mb_substr($chunk, 0, 1, 'UTF-8');
                // 处理每个字符，比如输出或者其他操作
                $c = "event:{$event_name}" . PHP_EOL; //定义事件
                $this_str_json = [
                    'title' => $char,
                ];
                $c .= "data:" . json_encode($this_str_json) . PHP_EOL; //推送内容
                echo $c . PHP_EOL;
                // 移除已处理的字符
                $chunk = mb_substr($chunk, 1, null, 'UTF-8');
            }

            // 存储剩余的字符
            $remainder = $chunk;

        }

        $c = "event:{$event_name}" . PHP_EOL; //定义事件
        $this_str_json = [
            'title' => $remainder,
        ];
        $c .= "data:" . json_encode($this_str_json) . PHP_EOL; //推送内容
        echo $c . PHP_EOL;

        $c = "event:{$event_name}" . PHP_EOL; //定义事件
        $c .= "data:end" . PHP_EOL; //推送内容
        echo $c . PHP_EOL;

        return 1;

    }


    public function embedding()
    {
        $client = new Client([
            'base_uri' =>'http://43.163.219.128:8000',
            'timeout' => 80,
        ]);

        try {
            $res = $client->request('post', '/embedding', [
                'json' => [
                    'filename' => './vscode.pdf',
                    'file_id' => '13',
                    'collection_name' => 'xx_vscode',
                    'openai_api_key' => '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'
                ],

            ]);
        } catch (\Exception $e) {

            dump($e->getMessage());
        }

        dump($res->getBody()->getContents());


    }


    public function kchat()
    {

        header('X-Accel-Buffering: no');
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');

        //跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type');

        set_time_limit(0); //防止超时
        ob_end_clean();
        ob_implicit_flush(1);

        $client = new Client([
            'base_uri' =>'http://43.163.219.128:8000',
            'timeout' => 80,
        ]);

        try {
            $res = $client->request('post', '/kchat', [
                'json' => [
                    'query' => input('keywords')?input('keywords'):'姓名，年龄是多少？',
//                    'collection_name' => 'xx_test'
                    'collection_name' => 'xx_vscode'
                ],
                'stream' => true,

            ]);
        } catch (\Exception $e) {

            dump($e->getMessage());
        }

        $body = $res->getBody();
        $remainder = '';
        while (!$body->eof()) {
            $chunk = $body->read(2);

            // 合并剩余的字符和当前的数据块
            $chunk = $remainder . $chunk;

            // 处理完整的字符
            while (mb_strlen($chunk, 'UTF-8') > 1) {
                $char = mb_substr($chunk, 0, 1, 'UTF-8');

                echo $char;
                // 移除已处理的字符
                $chunk = mb_substr($chunk, 1, null, 'UTF-8');
            }

            // 存储剩余的字符
            $remainder = $chunk;

        }

        echo $remainder;
        exit;

    }

    /**
     * @return string
     */
    public function publicPath()
    {
        return app()->getRootPath();
    }


    /**
     * @Apidoc\Title("测试订单完成")
     * @Apidoc\Query ("order_id", type="int", required=true, description="订单id")
     */
    public function completeOrder()
    {
        $order_id = input('order_id',0,'intval');
        $res = PayCommon::completeRobotOrder($order_id);
        return success('success',$res);

    }

    /**
     * @Apidoc\Title("测试添加订单code")
     */
    public function addCode()
    {
        $products = \app\common\model\Robot::select();
        foreach ($products as $product) {
            $product_id = $product->id;
            $product->code = md5(time() . rand(1000, 9999) .  $product_id );
            $product->save();
        }
        return 'success';
    }

    public function testJson()
    {
        $data = file_get_contents('123.txt');
        $bom = pack('H*','EFBBBF');
        $data = preg_replace("/^$bom/", '', $data);
        $data = json_decode($data,true);
        dump(json_last_error());
        dump(json_last_error_msg());
        dump($data);
    }


    /**
     * @Apidoc\Title("测试转移订单")
     */
    public function tranNewOrders()
    {

        $orders = Db::name('orders')->where('member_id','>',0)->select();
        foreach ($orders as $item){
            $product = PointProducts::find($item['point_products_id']);

            $new_order_data = [
                'name' => $product['name'],
                'member_id' => $item['member_id'],
                'payment_method' =>$item['payment_method'],
                'payment_time' => $item['create_time'],
                'purchase_type' => 'new',
                'total_amount' => $item['total_amount'],
                'payment_amount' => $item['total_amount'],
                'payment_details' => json_decode($item['details'],true),
                'product_parameters' => $product,
                'is_payment' => 1,
                'order_number' => $item['trade_no'],
                'is_apply_for_invoice' => 0,
                'product_type' => $product['is_integral']?'chatdog':'point',
                'create_time' => $item['create_time'],
            ];
            $order = \app\common\model\NewOrders::create($new_order_data);
        }

        return 'success';
    }

    /**
     * @Apidoc\Title("测试模版消息")
     * @throws \think\Exception
     *
     */
    public function testMsg()
    {
        WxTemplateMsg::send(1,5,[
            'thing44' => '测试',
            'time3' => '2022-12-12 12:12:12',
            'thing1' => '测试',
        ]);
        return 'success';
    }

    public function articleTest()
    {
        $client = new Client([
            'base_uri' => config('transfer.python_address'),
            'timeout' => 280,
            'verify' => false,
        ]);

        $gptToken = RobotsGptToken::order('update_time desc')->find();
        $gptToken->force(true)->save();
        $openai_api_key = $gptToken['name'];

        $json = [
            'title' => input('title'),
            'num' => input('num'),
            'openai_api_key' => $openai_api_key,
        ];



        try {
            $res = $client->post('/doArticle', [
                'json' => $json,
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage());
        }


        $body = $res->getBody()->getContents();


        return $body;
    }
}
